package com.itheima.contact.web;

import com.itheima.contact.domain.User;
import com.itheima.contact.service.UserService;
import com.itheima.contact.utils.CommonUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author ${Azer}
 * @LOVE,,,
 * @Date 2021/9/19 10:49
 */
@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        //从浏览器获取页面数据 存储到map集合中
//        Map<String, String[]> map = request.getParameterMap();



//        User user=new User();
//
//        //使用Beanutils工具类 把
//        // 集合中的数据封装到User对象中
//        try {
//            BeanUtils.populate(user,map);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }


        //使用重写的工具类 来优化代码
        User user = CommonUtils.CommonPopulate(User.class,request);

        //实例化业务层
        UserService userService=new UserService();
        //调用方法
        boolean result = userService.saveUser(user);
        if(result){
            //添加成功
            response.sendRedirect("/add_ok.jsp");
        }else {
            //添加失败
            //把失败信息存储到request域对象中
            request.setAttribute("error","邮箱重复");
            request.getRequestDispatcher("/add.jsp").forward(request,response);
        }

    }
}
